<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" :title="$t('newTranslation.finishedProductAdditional')"
				:rightText="$t('distributedEnter.scanRecord')" @clickRight="clickRight"
				@clickLeftBack="clickLeftBack"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="barcodeSplitting">
				<!-- 扫描条码部分 -->
				<view class="gui-bg-white gui-dark-bg-level-3 gui-padding-x distributed-head">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('Common.scanningInfo') }}
					</view>
					<view class="gui-form-item gui-border-b" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;">
							<text class="required-color">*</text>
							{{ $t('distributedEnter.barcodeScan') }}
						</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barCodes" type="search"
							:placeholder="$t('Common.scanningBarCode')" @confirm="confirm" @iconClick="iconClick">
						</uni-easyinput>
					</view>
				</view>

				<!-- 提示信息 -->
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6"
						style="padding-left:50rpx; padding-right:50rpx;">{{ $t('hardwareOut.barcodeInformation')
						}}</text>
					<view class="gui-title-line"></view>
				</view>

				<!-- 条码展示部分 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll">
					<view style="height: 15rpx"></view>
					<view class="card-boxCustom" v-if="data.cardShow&&data.scanInfo">
						<view class="card-body">
							<view class="custom-card-title">
								<text class="title-line"></text>{{ $t('distributedOut.atPresent') }}
							</view>
							<view class="custom-card-itemOne">
								<text class="item-info-title">{{ $t('distributedOut.barcode') }}：</text>{{data.scanInfo.barcode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('multilingual.productionLine') }}：</text>{{ data.scanInfo.productionLine }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialCode')
									}}：</text>{{ data.scanInfo.materialCode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialName')
									}}：</text>{{ data.scanInfo.materialName }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('distributedEnter.materialSpec') }}：</text>{{ data.scanInfo.materialSpec }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.qty')
									}}：</text>{{ data.scanInfo.qty }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.uom')
									}}：</text>{{ data.scanInfo.unit }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('translationImage.process') }}：</text>{{ data.scanInfo.process }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedOut.warehouse')
									}}：</text>{{ data.scanInfo.warehouse }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedOut.location')
									}}：</text>{{ data.scanInfo.location }}
							</view>
						</view>
					</view>
				</scroll-view>

				<!-- 底部确定按钮 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">{{ $t('calendar.submit') }}
					</view>
				</view>

				<!-- 普通弹窗 -->
				<uni-popup ref="popup" type="center">
					<view class="input-dialog-box" style="height:800rpx">
						<view class="input-dialog-content" style="margin-bottom: 280rpx;">
							<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
								<text class="item-info-title" style="width:400rpx"><text
										class="required-color">*</text>{{ $t('newTranslation.productionLine') }}：</text>
								<comboGrid requestUrl="/api1/wms/instock/GetFGProductionLine" v-model="data.productionLine"
									:requestParam="data.positionParam" inputKey="productionCode"
									:placeholder="$t('distributedEnter.placeholderTextChoose')"
									:gridPlaceholder="$t('Common.searchKeyWord')" :showInput="false"
									:column="data.columnPointPosition.column" bindValue="productionCode" :calculate="false"
									@setClick="getPointPositionClick">
								</comboGrid>
							</view>
							<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
								<text class="item-info-title" style="width:400rpx"><text
										class="required-color">*</text>{{ $t('newTranslation.fgmaterialCode') }}：</text>
								<comboGrid requestUrl="/api1/wms/instock/ProductionLineMaterial"
									v-model="data.fgmaterialCode" :requestParam="data.materialParam" :showInput="false"
									inputKey="materialCode" :placeholder="$t('distributedEnter.placeholderTextChoose')"
									:gridPlaceholder="$t('Common.searchKeyWord')" :column="data.columnMaterial.column" :calculate="false"
									bindValue="materialCode" @setClick="getMaterialClick">
								</comboGrid>
							</view>
							<view class="gui-form-item gui-border-b" style="padding: 20rpx 0;">
								<text class="item-info-title" style="padding-right: 40rpx;">
									<text class="required-color">*</text>
									{{ $t('distributedEnter.qty') }}
								</text>
								<uni-easyinput class="uni-mt-5" v-model="data.quantity" type="number"></uni-easyinput>
								<text>{{ data.unit }}</text>
							</view>
						</view>
						<view class="input-dialog-footer">
							<view class="input-dialog-button" @click="cancelFn">
								{{ $t('popup.cancel') }}
							</view>
							<view class="input-dialog-button dialog-button-left" @click="scanConfirmFn">
								{{ $t('popup.confirm') }}
							</view>
						</view>
					</view>
				</uni-popup>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
//引入文件
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import { ref, reactive, onMounted, computed, watch, toRaw } from "vue";
import { getFinishedProduct, updateD, saveFinishedProduct, selectWmsBarcodeInfoForFPSupplement } from '@/api/api.js'
import pdaScan from '@/hooks/pdaScan.js'
import storageBin from '@/components/storageBin.vue'
import comboGrid from '@/components/comboGrid.vue'
import { onBackPress } from '@dcloudio/uni-app';
import { useStore } from "vuex";
import { basPdaOperationLogFn } from '@/utils/index.js';
import { USERINFO, OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN } from '@/constant/index.js'

//JS国际化引入
import { useI18n } from 'vue-i18n';
//注册组件
components: { comboGrid }

const { t } = useI18n();
let store = useStore();
const { scan } = pdaScan();
// 弹框的属性
let popup = ref(null);

const data = reactive({
	barCodes: '',  // 条码
	barcodeList: [],// 扫描记录的存储
	productionLine: '',//产线
	productionLineName: '',//产线名
	fgmaterialCode: '',//成品代码
	scanInfo: {}, //当前扫描信息
	scanInfoItem: {}, //产线或者物料选择的数据存储
	unit: '', //单位
	columnPointPosition: { //产线的下拉里面显示字段
		column: [{
			label: t('newTranslation.productionLineName'), // 产出名称
			name: "productionName",
		}, {
			label: t('newTranslation.productionLineCode'), // 产出编码
			name: "productionCode",
		}]
	},
	columnMaterial: { //物料的下拉里面显示字段
		column: [{
			label: t('distributedEnter.materialName'), // 物料名称
			name: "materialName",
		},
		 {
			label: t('distributedEnter.materialCode'), // 物料编码
			name: "materialCode",
		}]
	},
	positionParam: {
		productionCode: ''
	},
	materialParam: {
		materialCode: "",
		productionLineCode:'JJGPDLine1'
	},
	materialId: null, // 物料id
	lineId: null, // 产线id
	materialArry: [],
	quantity: null
})

//
onMounted(() => {
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	// material()
})

// 存储扫描数据到vuex
data.barcodeList = computed(() => {
	return store.state.finishedProductAdditional
})

// 扫描条码事件
const confirm = () => {
	getCode(data.barCodes, 'keydown')
}

// 监听用户使用相机
const iconClick = async (type) => {
	if (type === 'suffix') {
		let code = await scan();
		getCode(code, 'scan')
	}
}
// 扫描条码获取信息
const getCode = (code, type) => {
	if (code.length <= 0) {
		uni.showToast({ title: t('newTranslation.correctly'), icon: 'none' });
		return
	}
	// 存储扫描的的条码,通过barode去判断是否有重复
	let arr = data.barcodeList.filter(x => x.barcode == code);

	if (arr.length > 0) {
		uni.showToast({ title: t('smashRemoval.codesRepeatedly'), icon: 'none' });
		return
	}
	data.barCodes = code;
	let parmes = {
		barcode: code
	}
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	selectWmsBarcodeInfoForFPSupplement(parmes).then(res => {
		uni.hideLoading();
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '成品补录'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code, //返回状态
				errorMessage: res.msg, //错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN,
				module:'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
			console.log(error)
		}
		if (res.code == 0) {
			// 打开弹框
			popup.value.open();
			data.scanInfo = {}
			data.productionLine=''
			data.fgmaterialCode=''
			data.quantity=''

		}
		else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})

}

// 获取成品料号
const material = (item) => {
	let str=item||''
	getFinishedProduct({
		current: 1,
		size: 100,
		productionLineCode:str
	}).then(res => {
		console.log(res)
		data.materialArry = res.data
		if(data.materialArry.length==1){
			data.fgmaterialCode=data.materialArry[0].materialCode
			data.scanInfoItem=data.materialArry[0]
			// data.fgmaterialCode=data.materialArry[0].materialCode

		}
	})
}

// 选择 产线
const getPointPositionClick = (x) => {
	// data.lineId = x.process_id
	data.productionLine = x.productionCode
	data.productionLineName = x.productionName
	data.materialParam.productionLineCode= x.productionCode
	// 调用物料获取编码
	material(x.productionCode)
	data.unit = 'box'  //这里单位暂时写死box
	// data.materialArry?.forEach(item => {

	// 	if (item.materialCode == data.fgmaterialCode) {

	// 		data.scanInfoItem = item
	// 		//data.materialId=item.id
	// 		//data.fgmaterialCode=item.materialCode
	// 		//data.materialParam.materialCode = item.materialCode;
	// 	}
	// })

}

const getMaterialClick = (x) => {
	// console.log(x)
	data.materialId = x.id
	data.fgmaterialCode = x.materialCode
	data.scanInfoItem = x
	data.materialParam.materialCode = x.materialCode;
}

// 弹框的确定按钮
const scanConfirmFn = () => {

	if (data.fgmaterialCode == '' || data.productionLine == '') {
		uni.showToast({ title: t('JsInternational.plsInformation'), icon: 'none' });
		return
	}
	console.log(data.quantity.length)
	if (data.quantity == null || data.quantity <= 0 || data.quantity.length == 0) {
		uni.showToast({ title: t('smashRemoval.pleaseEnterQty'), icon: 'none' });
		return
	}
	// console.log(data.scanInfoItem)
	// return
	// 物料信息
	data.scanInfo = Object.assign({}, data.scanInfoItem)
	// 产线及其他
	data.scanInfo.productionLine = data.productionLine
	data.scanInfo.productionName = data.productionLineName
	data.scanInfo.lineId = data.lineId

	data.scanInfo.qty = data.quantity
	data.scanInfo.barcode = data.barCodes
	data.scanInfo.unit = data.unit
	data.scanInfo.process = "JJG"
	data.scanInfo.warehouse = "JJG"
	data.scanInfo.location = "DR001"


	// 数据存储到vuex
	store.commit('addFinishedProductAdditional', data.scanInfo)


	data.cardShow = true
	popup.value.close();

	data.barCodes = " "

}

// 弹框的取消
const cancelFn = () => {
	popup.value.close()
	data.barCodes = ''
}

// 提交
const submit = () => {
	console.log(data.barcodeList)
	if (!data.barcodeList.length) {  //判断请扫描条码
		uni.showToast({
			title: t('stockManage.pleaseScanCode'),
			icon: 'none'
		})
		return
	}

	let parmes = []
	data.barcodeList.forEach(e => {
		var obj = {
			productionLineCode: e.productionLine,
			productionLineName: e.productionName,
			materialCode: e.materialCode,
			materialName: e.materialName,
			cartonNo: e.barcode,
			qty: e.qty
		}
		parmes.push(obj)

	})
	uni.showLoading({
		title: 'loading',
		mask: true
	});


	saveFinishedProduct({lstTrayInfo:parmes}).then((res) => {
		//隐藏加载框
		uni.hideLoading();
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '成品补录'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.code == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT,
				module:'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 200) {
			// 清空数据
			store.commit('clearFinishedProductStorage')
			data.scanInfo = undefined;
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });

		}
		else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}

//扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/barcodeManagement/finishedProductAdditionalRecord'
	})
}

//点击物理按键的返回
onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.barcodeList.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					//清除store 里面的数据
					store.commit("clearFinishedProductStorage");
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})

//导航栏左侧返回
const clickLeftBack = () => {
	navBackCheck()
}
const navBackCheck = () => {
	if (!data.barcodeList.length) {
		uni.navigateBack({
			delta: 1
		});
		return true
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.commit('clearFinishedProductStorage') // 清空条码数据
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}
</style>
